//
//  CLDiseaseDetailsController.m
//  CareLink
//
//  Created by whong7 on 16/8/18.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLDiseaseDetailsController.h"
#import "CLDiseaseStyleController.h"
#import "CLDiseaseStyleModel.h"
#import "CLSyndromeController.h"
#import "CLDiagnosisDetailsController.h"
#import "DoctorSelectTableViewController.h"

@interface CLDiseaseDetailsController ()

//网络请求管理器
@property(nonatomic,strong)CLNetworkManager *networkManager;
//疾病类型
@property (weak, nonatomic) IBOutlet UILabel *diseaseStyleLabel;
//疾病细分
@property (weak, nonatomic) IBOutlet UITextField *diseaseStyleField;
//并发症
@property (weak, nonatomic) IBOutlet UIButton *syndromeButton;
@property (weak, nonatomic) IBOutlet UILabel *syndromeLabel;
@property (weak, nonatomic) IBOutlet UITextField *syndromeField;
//并发症个数
@property (weak, nonatomic) IBOutlet UILabel *syndromeCountLabel;
//已确诊按钮
@property (weak, nonatomic) IBOutlet UIButton *diagnoseButton;
//疑似按钮
@property (weak, nonatomic) IBOutlet UIButton *symptomlessButton;
//接受过治疗按钮
@property (weak, nonatomic) IBOutlet UIButton *diagnosisButton;
//没有接受治疗按钮
@property (weak, nonatomic) IBOutlet UIButton *noDiagnosisButton;
//接收治疗的界面
@property (weak, nonatomic) IBOutlet UIView *diagnosisView;
//治疗方式显示
@property (weak, nonatomic) IBOutlet UITextField *diagnosisField;
//病情总字典
@property(nonatomic,strong)NSMutableDictionary *totalDetails;
//匹配到的医生数量
@property (weak, nonatomic) IBOutlet UILabel *doctorCountLabel;
//就诊申请按钮
@property (weak, nonatomic) IBOutlet UIButton *applyButton;

@end

@implementation CLDiseaseDetailsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ci1_id += 1;
    [self setupUI];
    
}



#pragma mark - 页面布局
-(void)setupUI
{
    //MARK:设置导航控制器
    
    //更改整个64的颜色 相当于是背景颜色
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithHex:0x20c6c6]];
    //系统内容渲染的颜色  navigationItem常用属性 title不管用，需要自己设定颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    //设置导航控制器标题
    self.navigationItem.title = @"疾病详情选择";
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:17] }];
    
    //设置预约须知
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"预约须知" style:UIBarButtonItemStyleDone  target:self action:@selector(noticeView)];
#warning mark ---------设置返回按钮文字为空
    // 设置返回的按钮的文字为空
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    
    
    //MARK:显示所选疾病科目
    NSDictionary *dict = @{@"1" : @"肿瘤" ,@"2" : @"心血管", @"3" : @"神经科", @"4" : @"血液科", @"5" : @"骨科"};
    //ci1_id 转化字符串
    NSString *idString = [NSString stringWithFormat:@"%ld",self.ci1_id];
    
    //记录所选病情科目
    [self.totalDetails setObject:idString forKey:@"ci1_id"];
    [self.totalDetails setObject:dict[idString] forKey:@"diseaseSubject"];
    //显示所选病情科目
    self.diseaseStyleLabel.text = [NSString stringWithFormat:@"疾病类型 ：%@",dict[idString]];
    
    //MARK:设置默认选项
    //已确诊
    [self diagnoseButton:self.diagnoseButton];
    //未接受治疗
    [self NoDiagnosisButton:self.noDiagnosisButton];
    //默认就诊过治疗方法：0--》2-手术治疗   3 – 保留治疗  4 –药物治疗
    [self.totalDetails setObject:@"0" forKey:@"diagnosis_type"];
    //默认并发症
    [self.totalDetails setObject:[NSArray new] forKey:@"complications"];
    //默认page
    [self.totalDetails setObject:@"1" forKey:@"page"];
    NSLog(@"%@",self.totalDetails);
}

#pragma mark - 跳转到预约须知页面
-(void)noticeView
{
    UIViewController *vc = [NSClassFromString(@"CLExceptionsController") new];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 疾病类型细分内容+细分模型
- (IBAction)diseaseSubdivideTouch:(id)sender {
    
    CLDiseaseStyleController *vc = [CLDiseaseStyleController new];
    
    //病情传输
    vc.totalDetails = self.totalDetails;
    
    //细分模型的回传数据
     __weak typeof(self) weakSelf = self;
    vc.inputCompeletionBlock = ^(CLDiseaseStyleModel *model) {
        weakSelf.diseaseStyleField.text = model.ci3_name;
    //记录病情选项
        NSString *ci2_id = [NSString stringWithFormat:@"%ld",model.ci2_id];
        NSString *ci3_id = [NSString stringWithFormat:@"%ld",model.ci3_id];
        [weakSelf.totalDetails setObject:ci2_id forKey:@"ci2_id"];
        [weakSelf.totalDetails setObject:ci3_id forKey:@"ci3_id"];
        
        //计算医生数量
        [weakSelf matchedDoctorCount];
        
        
        //重新清空并发症 显示框 + 清空 病情字典里面的 并发症
        weakSelf.syndromeField.text = @"";
        weakSelf.syndromeField.placeholder = @"请选择并发症(可以多选)";
        weakSelf.syndromeCountLabel.text = [NSString stringWithFormat:@"(共%d条)",0];
        weakSelf.syndromeLabel.text = @"";
        weakSelf.totalDetails[@"complications"]  = [NSMutableArray array];
        
        
    };
    
    //跳转到病情细分控制器
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 并发症 + 并发症模型
- (IBAction)diseaseSyndromeTouch:(id)sender {
    
    if (![self.totalDetails.allKeys containsObject:@"ci2_id"]) {
        [SVProgressHUD showImage:[UIImage imageNamed:@"warning"] status:@"请选择疾病细分"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];//只有none是可以继续用户交互的
        //延时
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;

    }
    
    
    
   CLSyndromeController *vc = [CLSyndromeController new];
    
    //病情传输
    vc.totalDetails = self.totalDetails;
    
    __weak typeof(self) weakSelf = self;
    vc.inputCompeletionBlock = ^(NSDictionary *dict)
    {

        NSLog(@"%@",dict);
        
        //创建临时数组
        NSMutableArray *array = [NSMutableArray array];
        
        if (dict.count != 0) {
           
            //拼接传回来的并发症
            NSMutableString *str1 = [NSMutableString string];
            
            for (NSString *key in dict) {
                
                if ([str1 isEqualToString:@"" ])
                {
                    [str1 appendFormat:@"%@",[dict objectForKey:key]];
                }
                else
                {
                    [str1 appendFormat:@",%@",[dict objectForKey:key]];
                }
                
                [array addObject:[dict objectForKey:key]];
                
            }
            
            //拼接字符串
            NSString *string = [NSString stringWithFormat:@"[%@]",str1];
            
            //传给textfiled显示
            weakSelf.syndromeField.text = @" ";
            weakSelf.syndromeCountLabel.text = [NSString stringWithFormat:@"(共%ld条)",dict.count];
            weakSelf.syndromeLabel.text = string;
            
        }
        else
        {
            //传给textfiled显示
            weakSelf.syndromeField.text = @"";
            weakSelf.syndromeField.placeholder = @"请选择并发症(可以多选)";
            weakSelf.syndromeCountLabel.text = [NSString stringWithFormat:@"(共%ld条)",dict.count];
            weakSelf.syndromeLabel.text = @"";
        }
        
        //病症汇总
        [weakSelf.totalDetails setObject:array forKey:@"complications"];

    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - 是否确诊
//已确诊
- (IBAction)diagnoseButton:(UIButton *)sender {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
    });
    
    sender.selected = YES;
    //当前button变大
    sender.transform = CGAffineTransformMakeScale(1.1, 1.1);


    self.symptomlessButton.selected = NO;
    //对立button变小
    self.symptomlessButton.transform = CGAffineTransformMakeScale(1, 1);

    
        //已经确诊
    [self.totalDetails setObject:@"1" forKey:@"is_confirmed"];

    //计算医生数量
    if (self.totalDetails[@"ci2_id"] != nil) {
        [self matchedDoctorCount];
    }
}
//症状疑似
- (IBAction)symptomlessButton:(UIButton *)sender {

    sender.selected = YES;
    //当前button变大
    sender.transform = CGAffineTransformMakeScale(1.1, 1.1);
    
    self.diagnoseButton.selected = NO;
    //对立button变小
    self.diagnoseButton.transform = CGAffineTransformMakeScale(1, 1);

    
    //没有确诊
    [self.totalDetails setObject:@"2" forKey:@"is_confirmed"];
    
    //计算医生数量
    if (self.totalDetails[@"ci2_id"] != nil) {
        [self matchedDoctorCount];
    }
}


#pragma mark - 是否接受过治疗

- (IBAction)DiagnosisButton:(UIButton *)sender{
    
    sender.selected = YES;
    sender.transform = CGAffineTransformMakeScale(1.1, 1.1);
    
    self.noDiagnosisButton.selected = NO;
    self.noDiagnosisButton.transform = CGAffineTransformMakeScale(1, 1);
    //接受过治疗
    [self.totalDetails setObject:@"1" forKey:@"has_diagnosis"];
    
    //显示接受治疗框
    self.diagnosisView.alpha = 1;
    
    //计算医生数量
    if (self.totalDetails[@"ci2_id"] != nil) {
        [self matchedDoctorCount];
    }
   }

- (IBAction)NoDiagnosisButton:(UIButton *)sender {
    sender.selected = YES;
    sender.transform = CGAffineTransformMakeScale(1.1, 1.1);
    
    self.diagnosisButton.selected = NO;
    self.diagnosisButton.transform = CGAffineTransformMakeScale(1, 1);
    
    //没有接受治疗
    [self.totalDetails setObject:@"2" forKey:@"has_diagnosis"];
    
    //默认就诊过治疗方法：0--》2-手术治疗   3 – 保留治疗  4 –药物治疗
    [self.totalDetails setObject:@"0" forKey:@"diagnosis_type"];
    //关闭接受治疗框
    self.diagnosisView.alpha = 0;
    //计算医生数量
    if (self.totalDetails[@"ci2_id"] != nil) {
        [self matchedDoctorCount];
    }

}

#pragma mark - 治疗信息选择
- (IBAction)diagnosisDetails:(UIButton *)sender {
    
    CLDiagnosisDetailsController *vc = [CLDiagnosisDetailsController new];
    
    __weak typeof(self) weakSelf = self;
    vc.inputCompeletionBlock = ^(NSDictionary *dict) {
        weakSelf.diagnosisField.text = dict.allValues[0];
        
        //病情记录
        [weakSelf.totalDetails setObject:dict.allKeys[0] forKey:@"diagnosis_type"];
        NSLog(@"%@",_totalDetails);
        
        if (weakSelf.totalDetails[@"ci2_id"] != nil) {
             [weakSelf matchedDoctorCount];
        }
       
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 计算医生数量

- (void)matchedDoctorCount
{
    NSString *url = @"http://iosapi.itcast.cn/matchedDoctorCount.json.php";
   //提取特征信息
    NSString *ci1_id = self.totalDetails[@"ci1_id"];
    NSString *ci2_id = self.totalDetails[@"ci2_id"];
    NSString *ci3_id = self.totalDetails[@"ci3_id"];
    NSString *diagnosis_type = self.totalDetails[@"diagnosis_type"];
    NSString *is_confirmed = self.totalDetails[@"is_confirmed"];
    NSDictionary *complications = self.totalDetails[@"complications"];
    NSString *has_diagnosis = self.totalDetails[@"has_diagnosis"];
    NSLog(@"%@",self.totalDetails);
    //根据特征信息 计算 医生数量
    NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",@"ci1_id":ci1_id,@"ci2_id":ci2_id,@"ci3_id":ci3_id,@"diagnosis_type":diagnosis_type,@"is_confirmed":is_confirmed,@"user_id":@(1000089),@"complications":complications,@"has_diagnosis":has_diagnosis};
    
    
    [self.networkManager POST:url parameters:paramDic success:^(id responseObject) {
        
     NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",response);
        //判断jsonData数据是否为nsnull，并显示医生数量
        if ((NSNull *)response[@"data"] != [NSNull null])
        {
            NSString *string = [NSString stringWithFormat: @"%@",response[@"data"][@"doctor_count"]];
            NSLog(@"%@",[string class]);
            self.doctorCountLabel.text = string;
            //有医生数量的时候 允许点击 申请按钮
            self.applyButton.userInteractionEnabled = YES;
            //button颜色改变
            self.applyButton.backgroundColor = [UIColor colorWithHex:0x20C6C6];
        }
        else
        {
            self.doctorCountLabel.text = @"0";
            //没有数量的时候 不允许点击 申请按钮
            self.applyButton.userInteractionEnabled = NO;
            //button颜色改变
            self.applyButton.backgroundColor = [UIColor colorWithHex:0xCCCCCC];
            
        }
        
        
        NSLog(@"%@",self.totalDetails);

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
    

}

#pragma mark - 就诊申请


- (IBAction)ApplyTouch:(UIButton *)sender {
    
    DoctorSelectTableViewController *vc = [DoctorSelectTableViewController new];
    
    vc.selectDictData = self.totalDetails;
    NSLog(@"%@",self.totalDetails);
    [self.navigationController pushViewController:vc animated:YES];

    
}


#pragma mark - 懒加载

-(NSMutableDictionary *)totalDetails
{
    if (_totalDetails == nil) {
        _totalDetails = [NSMutableDictionary dictionary];
    }
    return _totalDetails;
}

- (CLNetworkManager *)networkManager {
    
    if (_networkManager == nil) {
        
        _networkManager = [CLNetworkManager sharedManager];
        
    }
    return _networkManager;
    
}
-(void)dealloc
{

    // controller 销毁的时候，取消所有正在下载的线程
    [self.networkManager cancelOperations];
    NSLog(@"我去了");
}

@end